package me.flyray.bsin.server.impl;

import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.alipay.sofa.runtime.api.annotation.SofaServiceBinding;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import me.flyray.bsin.facade.service.BsinIntelligentDecisionEngine;
import me.flyray.bsin.server.context.DecisionEngineContextBuilder;
import me.flyray.bsin.server.domain.DecisionRule;
import me.flyray.bsin.server.mapper.DecisionRuleMapper;
import me.flyray.bsin.utils.BsinServiceInvokeUtil;
import me.flyray.bsin.utils.RespBodyHandler;


@SofaService(uniqueId = "${com.alipay.sofa.rpc.version}",
        bindings = {@SofaServiceBinding(bindingType = "bolt"),
                @SofaServiceBinding(bindingType = "rest")})
@Service("bsinIntelligentDecisionEngine")
public class BsinIntelligentDecisionEngineImpl implements BsinIntelligentDecisionEngine {

    @Autowired
    private DecisionEngineContextBuilder decisionEngineContextBuilder;
    @Autowired
    private DecisionRuleMapper decisionRuleMapper;
    @Autowired
    public BsinServiceInvokeUtil bsinServiceInvoke;

    /**
     * 1、根据决策模型编号和fact对象启动决策引擎
     * @param requestMap
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    public Map<String, Object> execute(Map<String, Object> requestMap) {
        String decisionModelCode = (String) requestMap.get("decisionModelCode");

        DecisionRule decisionRule = decisionRuleMapper.selectById("123456");
        // 1、构建决策引擎环境
        KieSession kieSession = decisionEngineContextBuilder.buildDecisionEngine(decisionRule,
                decisionRule.getKieBaseName() + "-session");
        //TODO  2、执行决策引擎，一个决策模型对应多个kieSession
        // 创建kieSession
//        StringBuilder resultInfo = new StringBuilder();
//        kieSession.setGlobal("resultInfo", resultInfo);
        // fact（事实对象，接收数据的对象实体类）
        kieSession.insert(requestMap);
        // 触发规则
        kieSession.fireAllRules();
        // 关闭KieSession
        kieSession.dispose();
        //TODO 获取命中的规则，执行规则计算
        // 根据决策状态和决策结果触发规则事件服务
        String serviceName = (String) requestMap.get("serviceName");
        String methodName = (String) requestMap.get("methodName");
        Map result = bsinServiceInvoke.genericInvoke(serviceName, methodName,null, requestMap);
        // 3、返回决策执行结果
        return RespBodyHandler.setRespBodyDto(result);
    }

}
